package org.linloong.modules.apis.disease.controller;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.linloong.config.audio.AudioServerProperties;
import org.linloong.config.audio.DifyAgentProperties;
import org.linloong.core.result.Result;
import org.linloong.utils.CheckLastResultCacheUtil;
import org.linloong.utils.VideoFeedUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Package: org.linloong.modules.apis.disease.controller.DiseaseVideoController
 * @Author: guxin
 * @CreateTime: 2025/10/19 17:48
 * @Description:
 * @Version: 3.0
 */
@Slf4j
@RestController
@RequestMapping("/api/disease/video")
@RequiredArgsConstructor
@Tag(name = "病虫害-视频")
@ApiSupport(order = 202)
public class DiseaseVideoController {
    @Autowired
    private AudioServerProperties serverProperties;
    @Autowired
    private DifyAgentProperties agentProperties;

    @PostMapping("/start")
    @Operation(summary = "上传视频进行病虫害检测")
    @ApiOperationSupport(order = 1)
    public Result<String> videoStart(@RequestParam MultipartFile video) {
//        videoStop();
        try (InputStream inputStream = video.getInputStream();) {
            try (HttpResponse response = HttpRequest.post(serverProperties.getDiseaseVideoUrl() + "/api/disease_video/upload_video")
                    .form("video", new InputStreamResource(inputStream, video.getOriginalFilename()))
                    .execute()) {
                log.info("视频处理结果: {}", response.body());
                return Result.success(JSON.parseObject(response.body()).getString("temp_file"));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

//    @PostMapping("/stop")
//    @Operation(summary = "停止病虫害检测")
//    @ApiOperationSupport(order = 2)
//    public Result<Boolean> videoStop() {
//        try (HttpResponse ignored = HttpRequest.post(serverProperties.getDiseaseVideoUrl() + "/api/disease_video/stop_processing").execute()) {
//            return Result.success(true);
//        }
//    }

    @GetMapping("/feed/{stream_id}")
    @Operation(summary = "获取病虫害检测视频流")
    @ApiOperationSupport(order = 3)
    public void videoFeed(@PathVariable String stream_id,
                          @RequestParam(defaultValue = "病虫害视频.mp4") String streamUrl,
                          HttpServletResponse response) {
        VideoFeedUtil.videoFeed(serverProperties.getDiseaseVideoUrl() + "/api/disease_video/video_feed?stream_url=" + streamUrl + "&stream_id=" + stream_id, 5, response);
    }

    @GetMapping("/latest/{stream_id}")
    @Operation(summary = "获取病虫害最新检测结果")
    @ApiOperationSupport(order = 4)
    public Result<JSONObject> videoLatest(@PathVariable String stream_id,
                                          @RequestParam(name = "debug", required = false, defaultValue = "false") Boolean debug) {
        CheckLastResultCacheUtil.addTask(stream_id,
                serverProperties.getDiseaseVideoUrl() + "/api/disease_video/latest_results?debug=" + debug + "&stream_id=" + stream_id,
                agentProperties, agentProperties.getFireAuth());
        return Result.success(CheckLastResultCacheUtil.getResult(stream_id));
    }
}
